import cv2
import numpy as np

"""
1.二值化图片
2.通过形态学对图像进行处理
"""

img = cv2.imread("C:\\Users\\86191\\Pictures\\Saved Pictures\\Camera Roll\\yb.jpg")
gary = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
# 二值化
ret,thresh = cv2.threshold(gary,0,255,cv2.THRESH_BINARY_INV+cv2.THRESH_OTSU)
# 开运算
kernel = np.ones((3,3),np.int8)
op = cv2.morphologyEx(thresh,cv2.MORPH_CLOSE,kernel,iterations=2)
# 膨胀
bg = cv2.dilate(op,kernel,iterations=1)

# 获取前景
dist = cv2.distanceTransform(op,cv2.DIST_L2,5)
# 二值化
rt,qg = cv2.threshold(dist,0.7*dist.max(),255,cv2.THRESH_BINARY)
qg = np.uint8(qg)
# 获取未知区域
unkown = cv2.subtract(bg,qg)
# 创建连通域
r,marker = cv2.connectedComponents(qg)
marker = marker + 1
marker[unkown==255] = 0
# 进行分割
result = cv2.watershed(img,marker)
img[result==-1] = [0,0,255]

cv2.imshow("watershed",img)
cv2.waitKey(0)

